package com.atguigu.gulimail.product.service.impl;

import com.atguigu.gulimail.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimail.product.dao.AttrGroupDao;
import com.atguigu.gulimail.product.dao.CategoryDao;
import com.atguigu.gulimail.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimail.product.entity.AttrGroupEntity;
import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;
import com.atguigu.gulimail.product.vo.AttrResponVo;
import com.atguigu.gulimail.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.product.dao.AttrDao;
import com.atguigu.gulimail.product.entity.AttrEntity;
import com.atguigu.gulimail.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
@Slf4j
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryService categoryService;


    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)? 0:1);

        if(catelogId != 0){
            queryWrapper.eq("catelog_id",catelogId);
        }

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            //attr_id  attr_name
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrResponVo> respVos = records.stream().map((attrEntity) -> {
            AttrResponVo attrRespVo = new AttrResponVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            //1、设置分类和分组的名字
            if("base".equalsIgnoreCase(type)){
                AttrAttrgroupRelationEntity attrId = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attrId != null && attrId.getAttrGroupId()!=null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrId.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }

            }


            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCateLogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(respVos);
        return pageUtils;
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();

        BeanUtils.copyProperties(attr,attrEntity);
        //保存基本数据
        this.save(attrEntity);

        AttrAttrgroupRelationEntity relationEntity=new AttrAttrgroupRelationEntity();
        //保存属性id,属性分组id
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        relationEntity.setAttrId(attrEntity.getAttrId());
        //保存关联关系
        relationDao.insert(relationEntity);

    }

    @Override
    public PageUtils queryBaseListPage(Map<String, Object> params,Long cateLogId) {

        QueryWrapper<AttrEntity> queryWrapper=new QueryWrapper<>();

        if(cateLogId!=0){
            queryWrapper.eq("catelog_id",cateLogId);
        }
        String key= (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.and((wapper)->{
                wapper.eq("attr_id",key)
                        .or()
                        .like("attr_name",key);
            });
        }
        IPage<AttrEntity> page=this.page(new Query<AttrEntity>().getPage(params)
                                        ,queryWrapper);

        PageUtils pageUtils=new PageUtils(page);

        List<AttrEntity> records =page.getRecords();

        List<AttrResponVo> responVos=records.stream().map((attrEntity)->{
            AttrResponVo attrResponVo=new AttrResponVo();

            BeanUtils.copyProperties(attrEntity,attrResponVo);

            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId())
            );
            if(relationEntity!=null){
                Long attrGroupId=relationEntity.getAttrGroupId();
                attrResponVo.setAttrGroupId(attrGroupId);
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>()
                        .eq("attr_group_id", attrGroupId));
                if (attrGroupEntity!=null){
                    attrResponVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectOne(new QueryWrapper<CategoryEntity>().eq("cat_id", attrEntity.getCatelogId()));
            if (categoryEntity!=null){
                attrResponVo.setCateLogName(categoryEntity.getName());
            }


            return attrResponVo;
        }).collect(Collectors.toList());

        pageUtils.setList(responVos);

        return pageUtils;
    }

    @Override
    public AttrResponVo getAttrInfo(Long attrId) {

        AttrEntity byId = this.getById(attrId);
        AttrResponVo attrResponVo=new AttrResponVo();

        BeanUtils.copyProperties(byId,attrResponVo);

        //在关联表中查询分组的Id
        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if(relationEntity!=null){
            attrResponVo.setAttrGroupId(relationEntity.getAttrGroupId());
            //根据分组id 查询分组名称
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
            if(attrGroupEntity!=null){
                attrResponVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        //查询分类的完整路径
        Long catelogId=byId.getCatelogId();
        List<Long> catelogPath = categoryService.findCatelogPath(catelogId);
        attrResponVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        attrResponVo.setCateLogName(categoryEntity.getName());
        return attrResponVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrResponVo attrResponVo) {
        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attrResponVo,attrEntity);
        this.updateById(attrEntity);

        //修改属性分组关联表  已有AttrGroupId
        AttrAttrgroupRelationEntity relationEntity=new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(attrResponVo.getAttrGroupId());
        relationEntity.setAttrId(attrResponVo.getAttrId());
        relationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_id",attrEntity.getAttrId()));

        Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_id", attrEntity.getAttrId()));
        if(count>0){
            relationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id",attrEntity.getAttrId()));
        }else{
            relationDao.insert(relationEntity);
        }
    }

    /**
     *  获取当前分组的所有没有关联的属性
     * @param param
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelation(Map<String, Object> param, Long attrgroupId) {

        //分组关联的属性,必须是自己所属分类当中的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
            //获取当前分组的所属分类
        Long cateId=attrGroupEntity.getCatelogId();
            //获取分类的其他分组
        List<AttrGroupEntity> groups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", cateId).ne("attr_group_id",attrgroupId));
        List<Long> groupIdlist = groups.stream().map((i) -> {
            return i.getAttrGroupId();
        }).collect(Collectors.toList());
            //获取其他分组的关联属性Id
        if(!groupIdlist.isEmpty()){
            List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIdlist));

            List<Long> attrIds = relationEntities.stream().map((i) -> {
                return i.getAttrId();
            }).collect(Collectors.toList());
            if (attrIds.size()>0){
                //不能显示本分组已经关联的属性
                List<AttrAttrgroupRelationEntity> relationEntitiesList = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
                    //获取已经关联的id
                List<Long> attrIdHavings = relationEntitiesList.stream().map((i) -> {
                    return i.getAttrId();
                }).collect(Collectors.toList());

                QueryWrapper<AttrEntity> queryWrapper=new QueryWrapper<>();
                queryWrapper.notIn("attr_id", attrIds).eq("attr_type",1).notIn("attr_id",attrIdHavings);
                String key=(String)param.get("key");
                if (StringUtils.isNotEmpty(key)){
                    queryWrapper.and((w)->{
                        w.eq("attr_id",key).or().like("attr_name",key);
                    });
                }
                IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(param), queryWrapper);
                return new PageUtils(page);

            }
            return null;
        }
        //当前分组只能关联别的分组没有关联的属性
        return null;
    }

}